package com.saas.tenant.interceptor;

import com.saas.tenant.context.TenantContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 租户信息拦截器
 * 从请求头 X-Tenant-ID 解析租户并写入上下文
 * 请求结束后自动清理，防止线程复用污染
 */
@Component
public class TenantInterceptor implements HandlerInterceptor {

    /**
     * 请求头常量
     */
    private static final String HEADER_TENANT_ID = "X-Tenant-ID";

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String tenantIdStr = request.getHeader(HEADER_TENANT_ID);
        if (tenantIdStr == null || tenantIdStr.isBlank()) {
            // 未带租户头直接拒绝，也可返回 400
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Missing required header '" + HEADER_TENANT_ID + "'");
            return false;
        }

        try {
            long tenantId = Long.parseLong(tenantIdStr);
            TenantContextHolder.setTenantId(tenantId);
            return true;
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Invalid tenant id format");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        // 请求结束务必清理
        TenantContextHolder.clear();
    }
}